#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RocketMQ 配置文件
"""

import os
import sys

# 默认配置模板
DEFAULT_CONFIG = {
    # NameServer地址
    "namesrv_addr": "",
    
    # ACL认证配置
    "access_key": "",
    "secret_key": "",
    
    # 生产者配置
    "producer_group": "demo_producer_group",
    
    # 消费者配置
    "consumer_group": "demo_consumer_group",
    
    # 默认主题
    "default_topic": "demo_topic",
    
    # 连接超时时间（秒）
    "timeout": 30,
    
    # 重试次数
    "retry_times": 3,
    
    # 消费者配置
    "consumer_config": {
        "orderly": False,  # 有序消费
        "message_tags": "*",  # 消息过滤标签，*表示所有标签
        "consume_timeout": 3000,  # 消费超时时间（毫秒）
        "channel": "ALIYUN",  # 通道名标识连接来源
    }
}

# 当前配置 - 从环境变量读取敏感信息
ROCKETMQ_CONFIG = {
    # NameServer地址 - 从环境变量读取
    "namesrv_addr": os.getenv("ROCKETMQ_NAMESRV_ADDR", ""),
    
    # ACL认证配置 - 从环境变量读取
    "access_key": os.getenv("ROCKETMQ_ACCESS_KEY", ""),
    "secret_key": os.getenv("ROCKETMQ_SECRET_KEY", ""),
    
    # 生产者配置
    "producer_group": "demo_producer_group",
    
    # 消费者配置
    "consumer_group": "demo_consumer_group",
    
    # 默认主题
    "default_topic": "demo_topic",
    
    # 连接超时时间（秒）
    "timeout": 30,
    
    # 重试次数
    "retry_times": 3,
    
    # 消费者配置
    "consumer_config": {
        "orderly": False,  # 有序消费
        "message_tags": "*",  # 消息过滤标签，*表示所有标签
        "consume_timeout": 3000,  # 消费超时时间（毫秒）
        "channel": "ALIYUN",  # 通道名标识连接来源
    }
}

# 消息配置
MESSAGE_CONFIG = {
    # 默认消息标签
    "default_tags": "demo",
    
    # 消息编码
    "encoding": "utf-8",
    
    # 消息压缩
    "compress": False,
}

# 日志配置
LOGGING_CONFIG = {
    "level": "INFO",
    "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    "file": None,  # 设置为文件路径可输出到文件
}

# 演示配置
DEMO_CONFIG = {
    # 发送消息数量
    "message_count": 10,
    
    # 消息间隔（秒）
    "message_interval": 1,
    
    # 消费等待时间（秒）
    "consume_timeout": 30,
    
    # 是否启用详细日志
    "verbose": True,
}


def check_config():
    """检查配置是否完整"""
    required_fields = ["namesrv_addr", "access_key", "secret_key"]
    missing_fields = []
    
    for field in required_fields:
        if not ROCKETMQ_CONFIG.get(field):
            missing_fields.append(field)
    
    return missing_fields


def get_user_input(prompt, default=""):
    """获取用户输入"""
    if default:
        user_input = input(f"{prompt} (默认: {default}): ").strip()
        return user_input if user_input else default
    else:
        return input(f"{prompt}: ").strip()


def configure_rocketmq():
    """配置 RocketMQ 连接信息"""
    print("\n" + "="*60)
    print("🚀 RocketMQ 配置向导")
    print("="*60)
    print("请配置 RocketMQ 连接信息：")
    print()
    
    # 检查当前配置
    missing_fields = check_config()
    
    if not missing_fields:
        print("✓ 配置已完整，当前配置：")
        print(f"  - NameServer: {ROCKETMQ_CONFIG['namesrv_addr']}")
        print(f"  - Access Key: {ROCKETMQ_CONFIG['access_key'][:8]}***" if ROCKETMQ_CONFIG['access_key'] else "  - Access Key: [未设置]")
        print(f"  - Secret Key: {ROCKETMQ_CONFIG['secret_key'][:8]}***" if ROCKETMQ_CONFIG['secret_key'] else "  - Secret Key: [未设置]")
        
        choice = input("\n是否要重新配置? (y/N): ").strip().lower()
        if choice not in ['y', 'yes', '是']:
            return True
    
    print("\n请按提示输入配置信息：")
    print("💡 提示：您也可以通过环境变量设置敏感信息：")
    print("   - ROCKETMQ_NAMESRV_ADDR: NameServer地址")
    print("   - ROCKETMQ_ACCESS_KEY: Access Key")
    print("   - ROCKETMQ_SECRET_KEY: Secret Key")
    print()
    
    # 获取 NameServer 地址
    while True:
        namesrv = get_user_input("NameServer 地址", ROCKETMQ_CONFIG.get("namesrv_addr", "localhost:9876"))
        if ":" in namesrv and namesrv.split(":")[1].isdigit():
            ROCKETMQ_CONFIG["namesrv_addr"] = namesrv
            break
        else:
            print("❌ 格式错误，请输入 host:port 格式，例如: localhost:9876")
    
    # 获取 Access Key
    access_key = get_user_input("Access Key", ROCKETMQ_CONFIG.get("access_key", ""))
    if access_key:
        ROCKETMQ_CONFIG["access_key"] = access_key
    
    # 获取 Secret Key
    secret_key = get_user_input("Secret Key", ROCKETMQ_CONFIG.get("secret_key", ""))
    if secret_key:
        ROCKETMQ_CONFIG["secret_key"] = secret_key
    
    # 可选配置
    print("\n可选配置（可直接回车使用默认值）：")
    
    topic = get_user_input("主题名称", ROCKETMQ_CONFIG.get("default_topic", "demo_topic"))
    ROCKETMQ_CONFIG["default_topic"] = topic
    
    producer_group = get_user_input("生产者组名", ROCKETMQ_CONFIG.get("producer_group", "demo_producer_group"))
    ROCKETMQ_CONFIG["producer_group"] = producer_group
    
    consumer_group = get_user_input("消费者组名", ROCKETMQ_CONFIG.get("consumer_group", "demo_consumer_group"))
    ROCKETMQ_CONFIG["consumer_group"] = consumer_group
    
    # 验证配置
    missing_fields = check_config()
    if missing_fields:
        print(f"\n❌ 配置不完整，缺少: {', '.join(missing_fields)}")
        print("💡 建议：将敏感信息设置为环境变量，避免硬编码在代码中")
        return False
    
    print("\n" + "="*60)
    print("✓ 配置完成！")
    print("="*60)
    print(f"NameServer: {ROCKETMQ_CONFIG['namesrv_addr']}")
    print(f"主题: {ROCKETMQ_CONFIG['default_topic']}")
    print(f"生产者组: {ROCKETMQ_CONFIG['producer_group']}")
    print(f"消费者组: {ROCKETMQ_CONFIG['consumer_group']}")
    print("="*60)
    
    return True


def save_config():
    """保存配置到文件"""
    try:
        config_content = f'''#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
RocketMQ 配置文件 - 自动生成
"""

import os

# RocketMQ连接配置
ROCKETMQ_CONFIG = {{
    # NameServer地址 - 从环境变量读取
    "namesrv_addr": os.getenv("ROCKETMQ_NAMESRV_ADDR", ""),
    
    # ACL认证配置 - 从环境变量读取
    "access_key": os.getenv("ROCKETMQ_ACCESS_KEY", ""),
    "secret_key": os.getenv("ROCKETMQ_SECRET_KEY", ""),
    
    # 生产者配置
    "producer_group": "{ROCKETMQ_CONFIG['producer_group']}",
    
    # 消费者配置
    "consumer_group": "{ROCKETMQ_CONFIG['consumer_group']}",
    
    # 默认主题
    "default_topic": "{ROCKETMQ_CONFIG['default_topic']}",
    
    # 连接超时时间（秒）
    "timeout": {ROCKETMQ_CONFIG['timeout']},
    
    # 重试次数
    "retry_times": {ROCKETMQ_CONFIG['retry_times']},
    
    # 消费者配置
    "consumer_config": {{
        "orderly": {ROCKETMQ_CONFIG['consumer_config']['orderly']},
        "message_tags": "{ROCKETMQ_CONFIG['consumer_config']['message_tags']}",
        "consume_timeout": {ROCKETMQ_CONFIG['consumer_config']['consume_timeout']},
        "channel": "{ROCKETMQ_CONFIG['consumer_config']['channel']}",
    }}
}}

# 消息配置
MESSAGE_CONFIG = {{
    "default_tags": "{MESSAGE_CONFIG['default_tags']}",
    "encoding": "{MESSAGE_CONFIG['encoding']}",
    "compress": {MESSAGE_CONFIG['compress']},
}}

# 日志配置
LOGGING_CONFIG = {{
    "level": "{LOGGING_CONFIG['level']}",
    "format": "{LOGGING_CONFIG['format']}",
    "file": {LOGGING_CONFIG['file']},
}}

# 演示配置
DEMO_CONFIG = {{
    "message_count": {DEMO_CONFIG['message_count']},
    "message_interval": {DEMO_CONFIG['message_interval']},
    "consume_timeout": {DEMO_CONFIG['consume_timeout']},
    "verbose": {DEMO_CONFIG['verbose']},
}}

# 配置检查函数
def check_config():
    """检查配置是否完整"""
    required_fields = ["namesrv_addr", "access_key", "secret_key"]
    missing_fields = []
    
    for field in required_fields:
        if not ROCKETMQ_CONFIG.get(field):
            missing_fields.append(field)
    
    return missing_fields

# 初始化时检查配置
if __name__ == "__main__":
    missing_fields = check_config()
    if missing_fields:
        print("⚠️  配置不完整，请设置以下环境变量：")
        for field in missing_fields:
            env_var = f"ROCKETMQ_{field.upper()}"
            print(f"   - {env_var}")
        print("\n或者运行 configure_rocketmq() 进行交互式配置")
    else:
        print("✓ 配置已完整")
'''
        
        with open(__file__, 'w', encoding='utf-8') as f:
            f.write(config_content)
        
        print("✓ 配置已保存")
        print("💡 注意：敏感信息已从配置文件中移除，请使用环境变量设置：")
        print("   - ROCKETMQ_NAMESRV_ADDR")
        print("   - ROCKETMQ_ACCESS_KEY") 
        print("   - ROCKETMQ_SECRET_KEY")
        
        return True
    except Exception as e:
        print(f"❌ 保存配置失败: {e}")
        return False


# 初始化时检查配置
if __name__ == "__main__":
    missing_fields = check_config()
    if missing_fields:
        print("⚠️  配置不完整，请运行 configure_rocketmq() 进行配置")
    else:
        print("✓ 配置已完整")
